package me.jessyan.mvparms.demo.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.platform.ai.control.BuildConfig;
import com.platform.ai.control.R;

import java.io.File;

public class UpdateApkUtil {
    public void showUpdateApkDialog(Context mContext,String versionString,String downloadLink){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mContext);
        normalDialog.setTitle("版本更新");
        normalDialog.setMessage("是否下载"+versionString+"最新版本?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //得到安装包的下载路径
                        String filePath = getInstallFilePath(mContext,versionString);
                        File installFile = new File(filePath);
                        if (installFile.exists()) {
                            //在已经下载好文件的情况下，根据下载路径直接安装
                            installApp(mContext,filePath);
                        } else {
                            //发现在安装包下载路径没有文件，需要下载
                            DownloadNewApk(mContext,versionString,downloadLink);
                        }
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    public void updateApkDialog(Context mContext,String versionString,String downloadLink){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        //得到安装包的下载路径
        String filePath = getInstallFilePath(mContext,versionString);
        File installFile = new File(filePath);
        if (installFile.exists()) {
            //在已经下载好文件的情况下，根据下载路径直接安装
            installApp(mContext,filePath);
        } else {
            //发现在安装包下载路径没有文件，需要下载
            DownloadNewApk(mContext,versionString,downloadLink);
        }
    }

    private String getInstallFilePath(Context mContext,String versionString) {
        String filePackagePath = mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/";
        String fileName = versionString + ".apk";
        String installFilePath = filePackagePath + fileName;
        return installFilePath;
    }

    //普通安装
    private void installApp(Context mContext,String apkPath) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //版本在7.0以上是不能直接通过uri访问的
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                File file = (new File(apkPath));
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", file);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(new File(apkPath)),
                        "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            mContext.startActivity(intent);
            //必须加入，不然不会显示安装成功界面
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载新apk
     */
    private void DownloadNewApk(Context context,String versionString,String downloadLink) {
        File installFile = new File(getInstallFilePath(context,versionString));
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(downloadLink);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDestinationUri(Uri.fromFile(installFile));
        long downloadId = downloadManager.enqueue(request);
        registerDownLoadFinishReceiver(context,downloadId,versionString);
        showDownloadDialog(context,downloadId,true);
    }

    private void registerDownLoadFinishReceiver(Context mContext,long downloadId,String versionString) {
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (downloadId == reference) {
                    // 下载完成后取消监听
                    context.unregisterReceiver(this);
                    // 安装应用
                    installApp(mContext,getInstallFilePath(mContext,versionString));
                }
            }
        };
        mContext.registerReceiver(receiver, filter);
    }


    private void showDownloadDialog(Context context,long downloadId,boolean mustUpdate) {
//        Dialog dialog = new Dialog(context, R.style.custom_dialog);
//        dialog.setOwnerActivity((Activity) context);
//        View contentView = LayoutInflater.from(context).inflate(R.layout.app_download_dialog, null);
//
//        ProgressBar progressBar = contentView.findViewById(R.id.pb_download_progress);
//
//        dialog.setContentView(contentView);
//        dialog.setCancelable(!mustUpdate);
//        dialog.setCanceledOnTouchOutside(!mustUpdate);
//        dialog.show();

        final int MAX_PROGRESS = 100;
        final ProgressDialog progressDialog =
                new ProgressDialog(context);
        progressDialog.setContentView(R.layout.pop_download);
        progressDialog.setProgress(0);
        progressDialog.setTitle("下载进度");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(MAX_PROGRESS);
        progressDialog.show();
        /* 模拟进度增加的过程
         * 新开一个线程，每个100ms，进度增加1
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
//                int progress= 0;
//                while (progress < MAX_PROGRESS){
//                    try {
//                        Thread.sleep(100);
//                        progress++;
//                        progressDialog.setProgress(progress);
//                    } catch (InterruptedException e){
//                        e.printStackTrace();
//                    }
//                }
//                // 进度达到最大值后，窗口消失
//                progressDialog.cancel();
                boolean downloading = true;

                while (downloading) {
                    DownloadManager.Query q = new DownloadManager.Query();
                    q.setFilterById(downloadId);
                    Cursor cursor = ((DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE)).query(q);
                    cursor.moveToFirst();
                    int bytes_downloaded = cursor.getInt(cursor
                            .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                    if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                        downloading = false;
                        progressDialog.dismiss();
                    }
                    final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
                    progressDialog.setProgress(dl_progress);
                    cursor.close();
                }
            }
        }).start();

    }


}
